package com.custom.blutoothtext

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.util.Log

class NetworkChangeReceiver : BroadcastReceiver() {
    private val TAG = "NetworkChangeReceiver"
    private var typeName = "" //记录网络状态字符串

    override fun onReceive(context: Context, intent: Intent) {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        if (networkInfo == null) {
            // WIFI 和 移动网络都关闭 即没有有效网络
            typeName = "当前无网络连接"
            if (callBackNetWork != null) {
                callBackNetWork!!.callBack(typeName)
            }
            Log.e(TAG, "当前无网络连接")
            return
        }
        if (networkInfo.type == ConnectivityManager.TYPE_WIFI) {
            /* typeName = networkInfo.getTypeName();//==> WIFI*/
            typeName = "当前正在使用WIFI" //==> WIFI
        } else if (networkInfo.type == ConnectivityManager.TYPE_MOBILE) {
            /*  typeName=networkInfo.getTypeName();*/
            typeName = "当前正在使用数据" //==> WIFI
        }
        if (callBackNetWork != null) {
            callBackNetWork!!.callBack(typeName)
        }
    }

    private var callBackNetWork: CallBackNetWork? = null

    fun setCallBackNetWork(callBackNetWork: CallBackNetWork?) { //公开接口 能访问接口
        this.callBackNetWork = callBackNetWork
    }

    interface CallBackNetWork {
        fun callBack(str: String?)
    }

}
